package com.zcy;

import com.espertech.esper.common.client.EventBean;
import com.espertech.esper.runtime.client.EPEventService;
import com.zcy.event.MyEvent;
import com.zcy.util.EsperBuilder;
import com.zcy.util.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.util.concurrent.TimeUnit;

/**
 * 14.3.15. Grouped Data Window (groupwin or std:groupwin)
 */
@Slf4j
public class GroupWindow extends TimeUtils {

    private static final String _GroupWindow = "@name('group_window') select amount, sum(num) from MyEvent#std:groupwin(amount)#length(2) group by amount";

    /**
     * 计算不同账户最后两次的钱
     */
    @Test
    public void uniqueWindowTest() {
        EsperBuilder esperBuilder = new EsperBuilder(_GroupWindow, new Class[]{MyEvent.class});

        esperBuilder.startCompile();

        EPEventService epEventService = esperBuilder.startDeploy((eventBeans, eventBeans1, epStatement, epRuntime) -> {
            for (int i = 0; i < eventBeans.length; i++) {
                EventBean eventBean = eventBeans[i];
                log.info("amount is:{}, sum is : {}", eventBean.get("amount"), eventBean.get("sum(num)"));
            }
        });

        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("001").name("001-name").num(10).build(), MyEvent.class.getSimpleName());
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("002").name("002-name").num(20).build(), MyEvent.class.getSimpleName());
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("002").name("002-name").num(30).build(), MyEvent.class.getSimpleName());
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("003").name("002-name").num(100).build(), MyEvent.class.getSimpleName());
        epEventService.sendEventBean(MyEvent.builder().timestamp(System.currentTimeMillis()).amount("002").name("002-name").num(40).build(), MyEvent.class.getSimpleName());

        sleep(TimeUnit.SECONDS, 40L);
    }

}
